﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Meta.Numerics.Statistics.Distributions;

namespace ExcelAddIn1
{
    /**
     * Implementation of a confidence interval test for datasets with unknown population stdev.
     */
    class Test_ConfidenceInterval : Test
    {
        public Test_ConfidenceInterval(DataContainer data)
        {
            this.data = data;
            res = new List<String>();
        }

        public override string GetInfo()
        {
            String s = "Calculates the confidence intervals for a dataset. ";
            s += "Requires that the data is normally distributed.";
            return s;
        }
            
        public override void RunTest()
        {
            res.Add("Confidence intervals");
            res.Add("");

            for (int i = 0; i < data.GetNoSets(); i++)
            {
                RunTest(i);
            }
        }

        public void RunTest(int i1)
        {
            DataSet d = data.GetDataSet(i1);

            double mean = d.GetMean();
            double n = d.GetN();
            double sum = d.GetSum();
            double sum2 = d.GetSquaredSum();

            //Calculate the standard error
            double s = Math.Sqrt( (sum2 - Math.Pow(sum,2) / n)/(n - 1.0) );
            double stdErr = s / Math.Sqrt(n);

            //Find critical T
            double DF = n - 1.0;

            StudentDistribution tdist = new StudentDistribution(DF);
            double Tcrit = tdist.InverseLeftProbability(1.0 - alpha / 2.0);

            //Find confidence interval
            double lower = mean - Tcrit * stdErr;
            double upper = mean + Tcrit * stdErr;

            res.Add(";" + d.GetName() + ";-");
            res.Add("N;" + d.GetN());
            res.Add("Mean;" + d.GetMean().ToString("F2"));
            res.Add("StDev;" + d.GetStDev().ToString("F2"));
            res.Add("Confidence;95%");
            res.Add("Lower bound;" + lower.ToString("F2"));
            res.Add("Upper bound;" + upper.ToString("F2"));
            res.Add(";;-");
        }
    }
}
